package com.imist.cake.servlet;

import com.imist.cake.entity.Cake;
import com.imist.cake.entity.Category;
import com.imist.cake.service.CakeService;
import com.imist.cake.service.CategoryService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

public class CakeServlet extends HttpServlet {
    private CakeService cakeService;
    private CategoryService categoryService;
    @Override
    public void init() throws ServletException {
        super.init();
        cakeService = new CakeService();
        categoryService = new CategoryService();
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if ("/cake/list.do".equals(req.getServletPath())){
            String categoryIdStr = req.getParameter("categoryId");
            Long categoryId = null;
            try {
                if (categoryIdStr != null){
                    categoryId = Long.valueOf(categoryIdStr);
                }
                //利用分页的方法，第一页显示全部内容
                List<Cake> cakes = cakeService.getCakeByCategoryId(categoryId,1,500);
                req.setAttribute("cakes",cakes);
                List<Category> categories = categoryService.getCategories();
                req.setAttribute("categories",categories);
                req.getRequestDispatcher("/WEB-INF/views/biz/cake_list.jsp").forward(req,resp);
            }catch (NumberFormatException e){
                req.getRequestDispatcher("/WEB-INF/views/biz/cake_list.jsp").forward(req,resp);
            }
        }else if ("/cake/addPrompt.do".equals(req.getServletPath())){
            List<Category> categories = categoryService.getCategories();
            req.setAttribute("categories",categories);
            req.getRequestDispatcher("/WEB-INF/views/biz/add_cake.jsp").forward(req,resp);

        }else if ("/cake/add.do".equals(req.getServletPath())){
            //当form表单中有multipart/form-data的时候也就是包含文件上传的时候，不可以用req.getParameter("")得到表单信息;
            req.setCharacterEncoding("utf-8");
            if (ServletFileUpload.isMultipartContent(req)){
                try{
                    FileItemFactory factory = new DiskFileItemFactory();
                    ServletFileUpload upload = new ServletFileUpload(factory);
                    //解析请求
                    List<FileItem> items = upload.parseRequest(req);
                    Iterator<FileItem> iterator = items.iterator();
                    Cake cake = new Cake();
                    while (iterator.hasNext()){//信息是普通格式，也就是普通表单的信息;
                        FileItem item = iterator.next();
                        if (item.isFormField()){
                            String filedName =  item.getFieldName();
                            if ("categoryId".equals(filedName)){
                                cake.setCategoryId(Long.valueOf(item.getString()));
                            }else if ("level".equals(filedName)){
                                cake.setLevel(Integer.valueOf(item.getString()));
                            }else if ("name".equals(filedName)){
                                cake.setName(new String(item.getString().getBytes("iso8859-1"),"utf-8"));
                            }else if ("price".equals(filedName)){
                                cake.setPrice(Integer.valueOf(item.getString()));
                            }
                        }else {//信息是文件格式
                            cake.setSmallImg(item.get());
                        }
                    }
                    cakeService.addCake(cake);
                    req.getRequestDispatcher("/cake/list.do").forward(req,resp);
                }catch (FileUploadException e){
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void destroy() {
        super.destroy();
        cakeService = null;
        categoryService = null;
    }
}
